package com.sxt.springsecuritytest2.configure; /*
 *
 * @Description todo
 * @author qqg
 * @date $date$
 * @param $params$
 * @return $return$
 **/

import com.sxt.springsecuritytest2.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfigure extends WebSecurityConfigurerAdapter
{
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//        auth.inMemoryAuthentication()
//                .withUser("user")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("USER");
       //使用数据库用户数据登陆
        auth.userDetailsService(sysUserService).passwordEncoder(bCryptPasswordEncoder);

    }

  protected void configure(HttpSecurity http) throws Exception {
        //关闭CSRF防御
        http.csrf().disable();
      http.authorizeRequests()
              //下面的路径不需要拦截
              .antMatchers("/","/login", "/fail", "/doLogin").permitAll()
              //所有的资源都需要有USER访问权限
//              .antMatchers("/**").hasAnyRole("USER")
              .anyRequest()
              .authenticated()
              .and()
              .formLogin()
              .loginPage("/").loginProcessingUrl("/login").failureForwardUrl("/fail").successForwardUrl("/success")
              .and().logout().logoutUrl("/logout")
              .invalidateHttpSession(true)
              .logoutSuccessUrl("/").permitAll();

          /*  http.formLogin()
                    .loginPage("/")
                    .loginProcessingUrl("/doLogin")
                    .successForwardUrl("/success")
                    .failureForwardUrl("/fail");
            http.authorizeRequests()
                    .antMatchers("/").permitAll()
                    .anyRequest().authenticated();
            http.csrf().disable();*/
    }

    //加入密码加密组件
    @Bean
    protected BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //
}
